import React, { useState, useEffect } from 'react';
import './AddForm.less'

import { Input, Button  } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {nanoid} from "nanoid"
export default function(props){


    const [inputArr, setInputArr] = useState([
        {id: 1, name: ''},
        // {id: 2, name: '222'},
        // {id: 3, name: '333'},
    ])

    const onChange = (value, id, index ) => {
        let a = JSON.parse(JSON.stringify(inputArr))
        // let b = a.map(m => ({...m, name: id === m.id ? value : null}))
        let b = a.filter(f => {
            if(f.id == id) {
                f.name = value
            }
            return f
        })
        setInputArr(b)
        props.getInputValue(b)
    }

    const addBtn = () => {  // 添加
        let a = JSON.parse(JSON.stringify(inputArr))
        let itemObj = {id: nanoid(), name: ''}
        a.push(itemObj)
        setInputArr(a)
    }

    const deleteBtn = (id, index) => {  // 删除
        let a = JSON.parse(JSON.stringify(inputArr))
        let b = a.filter(f => f.id !== id)
        setInputArr(b)
        props.getInputValue(b)
    }

  

  return (
    <div style={{padding: '20px'}} >
        组件
        <div style={{display: 'flex'}} >
            <div style={{marginRight: '12px'}} onClick={() => {
                console.log("input 里面的值", inputArr)
            }} > Passengers: </div>
            <div> 
                <div>
                    {inputArr.length == 0 ? (<div> 
                    <Input style={{width:'300px'}} placeholder="乘客 名字" /> <MinusCircleOutlined style={{color: '#c3c3c3', marginLeft: '6px', fontSize: '24px'}} 
                        onClick={deleteBtn}
                     />  
                </div> ) : (
                <div> 
                    { inputArr.length>0 &&  inputArr.map((item, index) => {
                        return ( <div style={{marginBottom: '10px'}} key={item.id} >
                            <Input 
                                style={{width:'300px'}} 
                                placeholder="乘客 名字" 
                                onChange={(e) => onChange(e.target.value, item.id, index)}
                            /> 

                            <MinusCircleOutlined style={{color: '#c3c3c3', marginLeft: '6px', fontSize: '24px'}} 
                                onClick={() => deleteBtn(item.id, index)}
                            />  
                        </div> )
                    } ) }
                </div> 
                )}
                </div>

                <div> 
                    <Button 
                        style={{width: '300px', marginTop: '10px'}} 
                        type="dashed" block
                        onClick={addBtn}
                    > 
                    <PlusOutlined />  Add field </Button> 
                </div>
            </div>
        </div>
    </div>
  )
}